package at.jaki.ubb.crawling.demo.db;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import at.jaki.ubb.crawling.api.DataInterpreter;
import at.jaki.ubb.crawling.demo.model.StringEntity;
import at.jaki.ubb.crawling.demo.model.UrlWithCount;
import at.jaki.ubb.crawling.demo.ui.UiManager;
import at.jaki.ubb.crawling.model.CEEntity;

public class Interpreter implements DataInterpreter {

	private static final int MORE_HITS_THEN = 2;

	public void notify(List<String> guids) {
		MockDataBase db = MockDataBase.getInstance();

		List<UrlWithCount> top = getTop(db.getElements());

		UiManager.getInstance().show(top);
	}

	private List<UrlWithCount> getTop(List<CEEntity> elements) {
		Map<CEEntity, Integer> map = new TreeMap<CEEntity, Integer>();

		int maxHits = MORE_HITS_THEN;

		for (CEEntity e : elements) {
			if (map.containsKey(e)) {
				Integer integer = map.get(e);
				map.put(e, integer + 1);
				if (integer == maxHits) {
					maxHits++;
				}
			} else {
				map.put(e, 1);
			}
		}
		List<UrlWithCount> list = new ArrayList<UrlWithCount>();
		for (Map.Entry<CEEntity, Integer> entry : map.entrySet()) {
			if (entry.getValue().compareTo(maxHits) >= 0) {
				UrlWithCount urlWithCount = new UrlWithCount();
				urlWithCount.setCount(entry.getValue());
				urlWithCount.setUrl(((StringEntity) (entry.getKey())).getString());
				list.add(urlWithCount);
			}
		}
		Collections.sort(list);
		Collections.reverse(list);
		return list;
	}
}
